import { getUserInfo } from '@/api/user'
import { GET_EMPLOYEE_NOTICE } from '@/http/public'
import { setTimeout } from 'core-js'

import { MessageBox, Message, Notification } from 'element-ui'
import { broadcast } from '@/utils/util'

const getDefaultState = () => {
  return {
    userInfo: {},
    connectCount: 0,
    maxConnectCount: 7,
  }
}

const state = getDefaultState()

const mutations = {
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
}

const actions = {
  // 获取用户信息
  getUserInfo({ commit, dispatch }) {
    return new Promise(async (resolve, reject) => {
      const res = await getUserInfo()

      if (!res.result) {
        return reject('获取用户信息失败')
      }

      commit('SET_USERINFO', res.data)

      //dispatch('connetWebSocket')
      dispatch('onConnect')

      resolve(res.data)
    })
  },

  // 开启定时器
  onConnect({ state, dispatch }) {
    let _this = this
    setInterval(function () {
      GET_EMPLOYEE_NOTICE().then((res) => {
        console.log(res)
        let list = res.data || []
        for (let i = 0, len = list.length; i < len; i++) {
          let k = list[i]
          setTimeout(function () {
            Notification({
              title: '新消息提醒',
              message: `${k.msg}${k.customerId?'<button type="primary" class="msg_follow_btn" size="mini">跟进</button>':''}`,
              type: 'success',
              duration: 0,
              dangerouslyUseHTMLString: true,
              onClick: function () {
                broadcast("look.user.follow", { data: { id: k.customerId }, list: [] });
              }
            })
          }, i * 100)
        }
      })
    }, 30 * 1000)
  },

  // 创建WebSocket连接
  connetWebSocket({ state, dispatch }) {
    const domain = state.userInfo.domain2 || ''
    const phone = state.userInfo?.loginMobile || '13632965527'
    if (!domain || !phone) return
    if ('WebSocket' in window) {
      const url = `ws://${domain}/crm/socket/${phone}`
      const ws = new WebSocket(url)

      ws.onopen = function () {
        console.log('WebSocket连接成功')
        console.log(url)
      }

      ws.onmessage = function (evt) {
        console.log('收到消息')
        console.log(evt.data)
        MessageBox.alert(evt.data, '新消息提醒', {
          confirmButtonText: '确定',
        })
      }

      ws.onerror = function (error) {
        console.log(`WebSocket连接失败`)
        console.log(error)
      }

      ws.onclose = function (e) {
        console.log(`websocket断开:${e.code}--${e.reason}--${e.wasClean}`)
        state.connectCount++
        if (state.connectCount > state.maxConnectCount) {
          return Message.error('WebSocket连接失败，请刷新尝试重连！')
        }
        setTimeout(() => {
          console.log('开始重新连接')
          dispatch('connetWebSocket')
        }, 2000)
      }
    } else {
      console.log('您的浏览器不支持WebSocket')
    }
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
